package com.xd.util;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.xd.util.Response.ResponseInfo;
import java.io.IOException;

public class SerializedTool {
    private String jsonString;

    public SerializedTool(String jsonString) {
        this.jsonString = jsonString;
    }

    public JsonNode path(String path) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(jsonString);
            String[] split = path.split("\\.");
            for(Integer i = 0; i < split.length; i++){
                String paramName = split[i];
                Integer index = paramName.indexOf("[");
                if(index > -1){
                    Integer paramIndex =
                        Integer.parseInt(
                            paramName.substring(index + 1, paramName.indexOf("]"))
                        );

                    paramName = paramName.substring(0, index);
                    ArrayNode arrayNode = (ArrayNode) jsonNode.get(paramName);
                    jsonNode = arrayNode.get(paramIndex);
                }
                else{
                    jsonNode = jsonNode.get(paramName);
                }
            }
            return jsonNode;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String format(String jsonString) {
        if(jsonString == null || jsonString.isEmpty()){
            return "";
        }
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
            JsonNode jsonNode = objectMapper.readTree(jsonString);
            return objectMapper.writeValueAsString(jsonNode);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonString;
    }

    public static <T> ResponseInfo deSerializedResponse(String jsonString, Class<T> valueType) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(jsonString);
            JsonNode responseNode = jsonNode.get("Response");
            JsonNode dataNode = responseNode.get("Data");
            ResponseInfo response = objectMapper.treeToValue(responseNode, ResponseInfo.class);
            T data = objectMapper.treeToValue(dataNode, valueType);
            response.setData(data);

            return response;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
